<template>
  <px-dialog v-model="dialogVisible" class="equip-dialog-wrap" title="操作日志" width="50%" align-center>
    <px-scrollbar class="container" height="300px" v-loading="loading">
      <div class="preview-content">
        {{ rowText }}
      </div>
    </px-scrollbar>
    <div class="footer">
      <px-button type="primary" @click="handleDownload">下载日志</px-button>
      <px-button @click="dialogVisible = false">关闭</px-button>
    </div>
  </px-dialog>
</template>
<script lang="ts" setup>
import { ref, onMounted } from "vue";
import { getCurrentInstance } from "vue";
import axios from "axios";
import { getToken } from "@/utils/auth";

const dialogVisible = defineModel();
const props = defineProps(["data"]);
// 页面本身的值
const { proxy }: any = getCurrentInstance();
const handleDownload = () => {
  const row = props.data || {};
  const params = {
    id: row.id,
    fileName: row.fileName
  };
  proxy.download("post", "/sharing/api/v1/file/download", params, row.originalName);
  dialogVisible.value = false;
};

const loading = ref<boolean>(false);
const rowText = ref();
const getFile = () => {
  loading.value = true;
  const row = props.data || {};
  const params = {
    id: row.id,
    fileName: row.fileName
  };
  axios({
    method: "post",
    url: "/ifp/sharing/api/v1/file/download",
    data: params,
    responseType: "arraybuffer", // 保留二进制原始数据
    headers: {
      "Content-Type": "application/json",
      Authorization: "Bearer " + getToken().accessToken || "",
      facCode: localStorage.getItem("facCode") || "",
      "Cache-Control": "no-cache" // 避免缓存旧数据
    }
  })
    .then(async res => {
      const textData = new TextDecoder("utf-8").decode(res.data);
      previewTxt(textData);
    })
    .catch(() => {
      loading.value = false;
    });
  loading.value = false;
};
onMounted(() => {
  getFile();
});
// txt
const previewTxt = data => {
  const text = data.replace(/\r\n|\n/g, match => match);
  rowText.value = text;
};
</script>
<style lang="scss" scoped>
.container {
  width: 100%;
  background: #f0f2f5;
  border-radius: 4px;
  padding: 12px;
}
/* 保留换行的核心样式 */
.preview-content {
  white-space: pre-wrap; /* 保留换行和空格 */
  word-break: break-word; /* 长文本自动换行 */
  color: #333;
}
.footer {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}
</style>
